package com.wxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxy.entity.Bill;
import com.wxy.entity.User;
import com.wxy.entity.vo.ConsumeVo;
import com.wxy.entity.vo.RefundVo;
import com.wxy.mapper.UserMapper;
import com.wxy.service.BillService;
import com.wxy.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tutu
 * @since 2022-11-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private BillService billService;

    @Override
    public User getBalance(String id) {
        User user = baseMapper.selectById(id);

        return user;
    }

    @Override
    @Transactional
    public void consume(ConsumeVo consumeVo) {
        Bill bill = new Bill();
        bill.setMoney(consumeVo.getMoney());
        bill.setCreateTime(new Date());
        bill.setUid(consumeVo.getUid());
        bill.setType(0);
        bill.setName(consumeVo.getName());
        billService.save(bill);
        User user = getById(consumeVo.getUid());
        user.setBalance(consumeVo.getBalance());
        baseMapper.updateById(user);

    }

    @Override
    public void refund(RefundVo refundVo) {
        QueryWrapper<Bill> wrapper = new QueryWrapper<>();
        wrapper.eq("id", refundVo.getId());
        wrapper.eq("uid", refundVo.getUid());
        Bill one = billService.getOne(wrapper);

        if (one == null){
            throw new RuntimeException("订单号信息不正确");
        }

        Bill bill = new Bill();
        bill.setMoney(refundVo.getMoney());
        bill.setUid(refundVo.getUid());
        bill.setCreateTime(new Date());
        bill.setType(1);
        bill.setName(one.getName());
        billService.save(bill);
        User user = getById(refundVo.getId());
        user.setBalance(user.getBalance().add(refundVo.getMoney()));
        updateById(user);


    }
}
